# encoding: utf-8
from __future__ import unicode_literals

from django.contrib.auth.models import User, Group, Permission
from django.db import models
from django.urls import reverse
from django.utils.encoding import python_2_unicode_compatible
from django.utils.safestring import mark_safe


@python_2_unicode_compatible
class Staff(User):
    def get_short_name(self):
        return self.first_name

    def get_full_name(self):
        return self.fullname()

    class Meta:
        proxy = True
        verbose_name = u'职员'
        verbose_name_plural = verbose_name
        # permissions = (('view_staff', u'Can view 职员'),)

    def __str__(self):
        return self.fullname()

    def fullname(self):
        if self.first_name is None and self.last_name is None:
            return self.username
        else:
            return u'%s%s' % (self.last_name, self.first_name)

    fullname.short_description = u'姓名'
    fullname.allow_tags = True
    fullname.is_column = True
    fullname.admin_order_field = 'first_name'

    def grouplist(self):
        return mark_safe('&nbsp;&nbsp;,&nbsp;&nbsp;'.join(['%s' % x for x in self.groups.all()]))

    grouplist.allow_tags = True
    grouplist.short_description = u'部门'
    grouplist.is_column = True
    grouplist.admin_order_field = 'groups'

    def is_group(self):
        return self.groups.filter(name=u'主管').exists()


@python_2_unicode_compatible
class Department(Group):
    class Meta:
        proxy = True
        verbose_name = u'部门'
        verbose_name_plural = verbose_name
        # permissions = (('view_department', u'Can view 部门'),)

    def __str__(self):
        return self.name

    def userlist(self):
        return mark_safe('&nbsp;&nbsp;,&nbsp;&nbsp;'.join(
            [u'%s%s' % (x.last_name, x.first_name) for x in self.user_set.filter(is_staff=True)]))

    userlist.allow_tags = True
    userlist.short_description = u'用户'
    userlist.is_column = True
    userlist.admin_order_field = 'user_set'


@python_2_unicode_compatible
class AccessControl(Permission):
    class Meta:
        proxy = True
        verbose_name = u'权限'
        verbose_name_plural = verbose_name
        # permissions = (('view_accesscontrol', u'Can view 权限'),)

    def __str__(self):
        return self.name


@python_2_unicode_compatible
class Host(models.Model):
    STATE_CHOICES = (('0', u'在线'), ('1', u'宕机'))
    description = models.CharField(u'描述', max_length=100)
    hostname = models.CharField(u'主机名', max_length=50)
    snmp_community = models.CharField(u'SNMP团体名称', max_length=50, default='wotone')
    snmp_port = models.IntegerField(u'SNMP端口', default=161)
    state = models.CharField(u'状态', max_length=1, default='0', choices=STATE_CHOICES)
    changed = models.DateTimeField(u'更新时间', blank=True, null=True)
    is_active = models.BooleanField(u'有效', default=True)

    class Meta:
        verbose_name = u'主机'
        verbose_name_plural = u'主机'

    def __str__(self):
        return self.description

    def operation(self):
        return u'<a href="%s">%s</a>' % (reverse('admin:core_host_port', args=[self.id]), u'添加端口')

    operation.short_description = u'操作'
    operation.allow_tags = True


@python_2_unicode_compatible
class Port(models.Model):
    STATE_CHOICES = (('0', u'开'), ('1', u'关'))
    DIRECT_CHOICES = (('0', u'流入'), ('1', u'流出'))
    host = models.ForeignKey('Host', on_delete=models.CASCADE, verbose_name=u'主机', related_name='ports')
    description = models.CharField(u'描述', max_length=100)
    name = models.CharField(u'名称', max_length=50)
    oid = models.CharField(u'OID', max_length=50)
    state = models.CharField(u'状态', max_length=1, choices=STATE_CHOICES, default='0')
    direct = models.CharField(u'方向', max_length=1, choices=DIRECT_CHOICES, default='0')
    is_active = models.BooleanField(u'有效', default=True)
    users = models.ManyToManyField('auth.user', verbose_name=u'可查看', related_name='ports', blank=True, null=True)
    primary = ('host', 'oid')

    class Meta:
        verbose_name = u'端口'
        verbose_name_plural = u'端口'
        unique_together = ('host', 'oid')

    def __str__(self):
        return u'%s - %s' % (self.host, self.description)


@python_2_unicode_compatible
class TrafficLog(models.Model):
    port = models.ForeignKey('Port', on_delete=models.CASCADE, verbose_name=u'描述', related_name='traffic_logs',
                             limit_choices_to={'host__is_active': True, 'is_active': True})
    date = models.DateTimeField(u'时间')
    traffic_in = models.BigIntegerField(u'流入(5分钟)')
    traffic_out = models.BigIntegerField(u'流出(5分钟)')
    in_bits = models.DecimalField(u'流入(b/s)', max_digits=15, decimal_places=2, blank=True, null=True)
    out_bits = models.DecimalField(u'流出(b/s)', max_digits=15, decimal_places=2, blank=True, null=True)
    isvalid = models.BooleanField(u'有效记录', default=True)
    # primary = ('port', 'date')   # 去除重复

    class Meta:
        verbose_name = u'流量记录'
        verbose_name_plural = u'流量记录'
        ordering = ['-date']

    def __str__(self):
        return u'%s %s' % (self.port.description, self.date)

    def name(self):
        return self.port.name

    name.short_description = u'端口'
    name.allow_tags = True
    name.is_column = True
    name.admin_order_field = 'port'


@python_2_unicode_compatible
class TrafficChart(TrafficLog):
    class Meta:
        proxy = True
        verbose_name = u'流量图'
        verbose_name_plural = u'流量图'
        ordering = ['-date']

    def __str__(self):
        return u'%s %s' % (self.port.description, self.date)


@python_2_unicode_compatible
class Collection(models.Model):
    date = models.DateTimeField(u'时间')
    host = models.ForeignKey('Host', on_delete=models.CASCADE, verbose_name=u'主机', related_name='collections')
    is_active = models.BooleanField(u'有效', default=True)
    message = models.CharField(u'描述', max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = u'采集日志'
        verbose_name_plural = u'采集日志'
        ordering = ['-date']

    def __str__(self):
        return u'%s %s' % (self.host.description, self.date)

    def name(self):
        return self.host.description

    name.short_description = u'主机'
    name.allow_tags = True
    name.is_column = True
    name.admin_order_field = 'host'

    def ip(self):
        return self.host.hostname

    ip.short_description = u'IP'
    ip.allow_tags = True
    ip.is_column = True
    ip.admin_order_field = 'host'


# @python_2_unicode_compatible
# class AdvancedSearch(models.Model):
#     started = models.DateTimeField(u'开始时间', null=True, blank=True)
#     expired = models.DateTimeField(u'开始时间', null=True, blank=True)
